package main

import (
	"bytes"
	"encoding/csv"
	"encoding/json"
	"io/ioutil"
	"log"

	"net/http"
	"os"
	"os/exec"
	"time"
)

func main() {
    // 读取csv
    file := "log.csv"
    fh, err := os.Open(file)
    if err != nil {
        log.Fatalf("csv文件打开失败")
    }
    reader := csv.NewReader(fh)
    // 小文件读取所有
    content, err := reader.ReadAll()
    if err != nil {
        log.Println(err)
    }
    fh.Close()
    fh, err = os.OpenFile("log1.csv", os.O_RDWR | os.O_CREATE, 0666)
    if err != nil {
        log.Println(err)
    }
    defer fh.Close()
    writer := csv.NewWriter(fh) 
    timeLayout := "1月2日"
    for _, row := range content {
        // log.Println(row)
        // 发送钉钉后状态改变
        // log.Println(row[0], time.Now().Format(timeLayout))
        if time.Now().Format(timeLayout) == row[0] && row[2] != "1" {
            if sendDing(row[1]) {
                row[2] = "1"
            }
        }
        writer.Write(row)
    }
    writer.Flush()
    c := exec.Command("bash", "-c", "mv -f log1.csv log.csv")
    output, err := c.CombinedOutput()
    if err != nil {
        log.Println(err)
    }
	log.Println(string(output))
}

type DingMsg struct {
    Msgtype string `json:"msgtype"`
    Text Content `json:"text"`
    At At `json:"at"`
}

type Content struct {
    Content string `json:"content"`
}

type At struct {
    AtMobiles []string `json:"atMobiles"`
}

func sendDing(name string) bool {
    var phones []string
    namePhone := map[string]string{
        "二哥": "15173405742",
        "陈磊": "17688929199",
        "朱波波": "17607173230",
        "吴勇祥": "15639132368",
        "钟益宏": "15814951773",
    }
    timeLayout := "1月02日"
    text := "market --- " + time.Now().Format(timeLayout) + "\n"
    text = text + "今天轮到你:" + name + " 值班检查日志,"
    text = text + "检查地址在钉钉文档"
    phones = append(phones, namePhone[name])
    dingMsg := DingMsg{
        Msgtype: "text",
        Text: Content{Content: text},
        At: At{AtMobiles: phones},
    }
    // log.Println(dingMsg)
    data, err := json.Marshal(dingMsg)
    if err != nil {
        log.Println(err)
    }
    url := "https://oapi.dingtalk.com/robot/send?access_token=3dda6f9337187ee4e484002f2a1bd2846df228b58ffb327a7cdb7ec08f694c28";
    // log.Println(string(data))
    resp, err := http.Post(url, "application/json", bytes.NewBuffer(data))
    if err != nil {
        log.Println(err)
    }
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    log.Println(string(body))
    return true
}
